import 'package:flutter/material.dart';
import 'package:flutter_design/utils/logger/logger.dart';
import '../../../app/app_services.dart';
import '../../../app/environment_config.dart';
import '../viewmodels/search_viewmodel.dart';
import '../models/repo_model.dart';

class SearchPage extends StatefulWidget {
  const SearchPage({super.key});

  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  late final SearchViewModel _viewModel;
  final TextEditingController _controller = TextEditingController();

  @override
  void initState() {
    super.initState();
    // 初始化 ViewModel
    _viewModel = SearchViewModel();
    // 添加监听器！当 ViewModel 调用 notifyListeners() 时，会执行 _onViewModelChanged
    _viewModel.addListener(_onViewModelChanged);
    init();
  }

  Future<void> init() async {
    final enable = await AppServices.cache.get("enable");
    Logger.info("init", "for cache enable: $enable");
    if(EnvironmentConfig.isProduction){
      if(EnvironmentConfig.config.apiSuffix != null){
        EnvironmentConfig.resetApiSuffix();
      }
      await _viewModel.getEnv();
    }
  }

  // 当 ViewModel 变化时，这个方法会被调用
  void _onViewModelChanged() {
    // 调用 setState 会触发 build 方法，从而用新数据重建 UI
    setState(() {});
  }

  @override
  void dispose() {
    Logger.info("Search", "apiSuffix:${EnvironmentConfig.config.apiSuffix }");
    // 4. 在页面销毁时，移除监听器并释放 ViewModel，防止内存泄漏
    _viewModel.removeListener(_onViewModelChanged);
    _viewModel.dispose();
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('GitHub Repo Search'),
      ),
      body: Column(
        children: [
          _buildSearchInput(),
          Expanded(child: _buildBody()),
        ],
      ),
    );
  }

  // 搜索输入框
  Widget _buildSearchInput() {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: TextField(
        controller: _controller,
        decoration: InputDecoration(
          labelText: 'Search for repositories...',
          suffixIcon: IconButton(
            icon: const Icon(Icons.search),
            onPressed: () {
              // 5. 将用户操作委托给 ViewModel
              _viewModel.searchRepositories(_controller.text);
              FocusScope.of(context).unfocus(); // 收起键盘
            },
          ),
          border: const OutlineInputBorder(),
        ),
        onSubmitted: (value) {
          _viewModel.searchRepositories(value);
        },
      ),
    );
  }

  // 根据 ViewModel 的状态显示不同内容
  Widget _buildBody() {
    // 6. 根据 ViewModel 的状态来构建 UI
    switch (_viewModel.state) {
      case ViewState.loading:
        return const Center(child: CircularProgressIndicator());
      case ViewState.error:
        return Center(
          child: Text(
            'An error occurred: ${_viewModel.errorMessage}',
            style: const TextStyle(color: Colors.red),
          ),
        );
      case ViewState.success:
        return _buildRepoList(_viewModel.repos);
      case ViewState.idle:
      return const Center(child: Text('Enter a query to search.'));
    }
  }

  // 结果列表
  Widget _buildRepoList(List<Repo> repos) {
    if (repos.isEmpty) {
      return const Center(child: Text('No repositories found.'));
    }
    return ListView.builder(
      itemCount: repos.length,
      itemBuilder: (context, index) {
        final repo = repos[index];
        return Card(
          margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          child: ListTile(
            leading: CircleAvatar(
              backgroundImage: NetworkImage(repo.owner.avatarUrl),
            ),
            title: Text(repo.fullName),
            subtitle: Text(
              repo.description ?? 'No description',
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
            trailing: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Icon(Icons.star, color: Colors.amber, size: 16),
                const SizedBox(width: 4),
                Text(repo.stargazersCount.toString()),
              ],
            ),
            onTap: () {
              // TODO: 可以在这里导航到详情页
              // Navigator.push(...);
            },
          ),
        );
      },
    );
  }
}
